package vip.liux.gateway.filters.auditlog;

import java.time.LocalDateTime;
import java.util.LinkedList;
import java.util.List;

public class InMemoryAuditRequestLogRepository implements AuditRequestLogRepository {

    private static final int DEFAULT_CAPACITY = 1000;

    private final Object monitor = new Object();

    private AuditRequestLog[] logs;

    private volatile int tail = -1;

    public InMemoryAuditRequestLogRepository() {
        this(DEFAULT_CAPACITY);
    }

    public InMemoryAuditRequestLogRepository(int capacity) {
        this.logs = new AuditRequestLog[capacity];
    }

    public void setCapacity(int capacity) {
        synchronized (this.monitor) {
            this.logs = new AuditRequestLog[capacity];
        }
    }

    @Override
    public void add(AuditRequestLog log) {
        if (log == null) {
            throw new IllegalArgumentException("AuditRequestLog must not be null");
        }
        synchronized (this.monitor) {
            this.tail = (this.tail + 1) % this.logs.length;
            this.logs[this.tail] = log;
        }
    }

    @Override
    public List<AuditRequestLog> find(String serviceName, LocalDateTime after) {
        LinkedList<AuditRequestLog> result = new LinkedList<>();
        synchronized (this.monitor) {
            for (int i = 0; i < this.logs.length; i++) {
                AuditRequestLog log = resolveTailLog(i);
                if (log != null && isMatch(serviceName, after, log)) {
                    result.addFirst(log);
                }
            }
        }
        return result;
    }

    private boolean isMatch(String serviceName, LocalDateTime after, AuditRequestLog log) {
        boolean match = serviceName == null || log.getServiceName().equals(serviceName);
        return match && (after == null || log.getExecutionTime().isAfter(after));
    }

    private AuditRequestLog resolveTailLog(int offset) {
        int index = ((this.tail + this.logs.length - offset) % this.logs.length);
        return this.logs[index];
    }
}